/**
 * UserActivityLogAdvisor.java
 * 
 * Copyright@2015 OVT Inc. All rights reserved. 
 * 
 * May 29, 2015
 */
package com.ovt.doorbell.payment.api.advisor;

import java.text.MessageFormat;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ovt.doorbell.payment.common.log.Logger;
import com.ovt.doorbell.payment.common.log.LoggerFactory;
import com.ovt.doorbell.payment.common.utils.DataConvertUtils;
import com.ovt.doorbell.payment.dao.config.AppProperties;
import com.ovt.doorbell.payment.dao.constant.LoggerConstants;
import com.ovt.doorbell.payment.dao.vo.User;
import com.ovt.doorbell.payment.service.context.SessionContext;

/**
 * UserActivityLogAdvisor
 * 
 * @Author zhi.liu
 * @Version 1.0
 * @See
 * @Since [OVT Cloud Platform]/[API] 1.0
 */
@Component
@Aspect
public class UserActivityLogAdvisor
{
    private User currentUser;

    private static final Logger logger = LoggerFactory
            .getLogger(LoggerConstants.USER_ACTIVITY_LOGGER); 
    
    private static final String POINTCUT = "execution(public * com.ovt.api.controller.*.*(..)) "
            + "AND !execution(* com.ovt.api.controller.ServiceAccessController.*(..)) "
            + "OR execution(public * com.ovt.service.manager.*.*(..))";

    @Autowired
    private AppProperties appProperties;

    @Before(value = POINTCUT)
    public void logEntering(JoinPoint jp)
    {
        if (!appProperties.logUserActivityEnable)
        {
            return;
        }

        String userInfo = getCurrenrUserInfo();

        
        logger.entering(jp.getClass().getName(), jp.getSignature().getName(),
                DataConvertUtils.toString(jp.getArgs()), userInfo);
    }
    
    @AfterReturning(value = POINTCUT, returning = "returnValue")
    public void logExiting(JoinPoint jp, Object returnValue)
    {
        if (!appProperties.logUserActivityEnable)
        {
            return;
        }

        String userInfo = getCurrenrUserInfo();

        logger.exiting(jp.getClass().getName(), jp.getSignature().getName(),
                returnValue, userInfo);
    }

    /**
     * Get current user string info.
     * 
     * @return
     */
    private String getCurrenrUserInfo()
    {
        currentUser = SessionContext.getCurrentUser();
        String userInfo = "";
        if (currentUser != null)
        {
            userInfo =
                    MessageFormat.format("- User:[{0}]", currentUser.getId());
        }
        return userInfo;
    }

}
